﻿using Newtonsoft.Json;

namespace Service.Framework.Utils
{
    public class JsonConverterDatetime : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime) || objectType == typeof(DateTime?);
        }

        /// <summary>
        /// 读JSON（反序列化）
        /// </summary>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            switch (reader.TokenType)
            {
                case JsonToken.Null:
                    return null;

                case JsonToken.String:
                    var strValue = reader.Value?.ToString();
                    if (string.IsNullOrWhiteSpace(strValue))
                    {
                        return null;
                    }
                    if (DateTime.TryParse(strValue, out var parsedDate))
                    {
                        return parsedDate;
                    }
                    return null;

                case JsonToken.Date:
                    return (DateTime)reader.Value;

                default:
                    throw new JsonSerializationException(
                        $"Unexpected token {reader.TokenType} when parsing date. Path: {reader.Path}");
            }
        }

        /// <summary>
        /// 写JSON（序列化）
        /// </summary>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
            }
            else if (value is DateTime dateTime)
            {
                if (dateTime == default(DateTime))
                {
                    writer.WriteNull();
                }
                else
                {
                    writer.WriteValue(dateTime);
                }
            }
        }
    }

}
